import os
import requests

# 使用 Session 对象来模拟浏览器会话
session = requests.Session()

# 设置请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

# 访问首页以获取必要的 Cookie
home_url = "https://www.douyin.com/"
home_response = session.get(home_url, headers=headers)
home_response.raise_for_status()

# 获取视频链接
url = "https://www.douyin.com/aweme/v1/play/?video_id=v0200fg10000ct0qi87og65vb16piamg&line=0&file_id=43eb67d22ee444209fd10ce9ae54b516&sign=4641b795d1c0fe28eeb7323b19bdfe51&is_play_url=1&source=PackSourceEnum_PUBLISH"

try:
    # 发送请求
    response = session.get(url, headers=headers, stream=True)
    response.raise_for_status()  # 检查请求是否成功

    # 检查响应状态码
    print(f"Response status code: {response.status_code}")

    # 读取响应内容并存储
    content = response.content
    print(f"Response content length: {len(content)} bytes")

    # 如果需要保存到文件
    if not os.path.exists("./video"):
        os.makedirs("./video")

    with open(f"./video/video.mp4", "wb") as file:
        file.write(content)
        file.flush()  # 确保数据立即写入磁盘

    print("视频下载完成")

except requests.exceptions.RequestException as e:
    print(f"请求时发生错误: {e}")
except IOError as e:
    print(f"写入文件时发生错误: {e}")
